package com.cy.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author ChenYan
 * @Date 2021/8/13 13:55
 * @Description
 */
public class StaticResourceUtil {

    /**
     * 获取静态资源绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replace("\\\\", "/") + path;
    }

    /**
     * 通过输出流输出静态资源
      * @param fileInputStream
     * @param outputStream
     */
    public static void outputStaticResource(FileInputStream fileInputStream, OutputStream outputStream) throws IOException {
        int count = 0;

        while (count == 0){
            count = fileInputStream.available();
        }
        //输出HttpHeader
        outputStream.write(HttpProtocolUtil.getHttpHeader200(count).getBytes());

        //读取内容输出
        int writelen = 0;
        int byteSize = 1024;

        byte[] bytes = new byte[byteSize];

        while (writelen < count){
            //如果大于文件大小表示是最后一次
            if ((writelen + byteSize) > count){
                byteSize = count - writelen;
                bytes = new byte[byteSize];
            }
            //输入流读到Byte数组
            fileInputStream.read(bytes);
            //输出流输出byte数组
            outputStream.write(bytes);
            outputStream.flush();

            writelen += byteSize;
        }

    }
}
